package dao;

import com.mongodb.WriteResult;
import entity.Cart;
import entity.Product;
import entity.User;
import org.bson.types.ObjectId;
import org.junit.Test;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.FindOptions;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import util.MorphiaUtil;

import java.util.List;

public class CartDAO {
    //用户添加商品前判断是否存在该商品
    public void insertCart(Cart cart) {
        Datastore ds = MorphiaUtil.getDB();
        Cart existCart =findByUIdAndPId(cart.getUserId(), cart.getProductId());
        if (existCart != null) {
            Query<Cart> cartQuery = ds.createQuery(Cart.class).filter("userId", cart.getUserId()).filter("productId", cart.getProductId());
            UpdateOperations<Cart> cartUpdate = ds.createUpdateOperations(Cart.class).inc("num", cart.getNum());
            ds.update(cartQuery, cartUpdate);
        }else {
            ds.save(cart);
        }
    }
    @Test
    public void insertCart() {
        UserDAO1 userDao = new UserDAO1();
        ObjectId userID = new ObjectId("66939990d3c8145b2aa0e2a2");
        User user = userDao.findById(userID.toString());
        ProductDAO productDao = new ProductDAO();
        ObjectId productID = new ObjectId("669386eb0144e66fd4b7e1cd");
        Product product = productDao.findById(productID);
        Cart cart = new Cart(userID,user.getUsername(), productID,product.getName(),product.getPrice(), 2);
        CartDAO cartDAO = new CartDAO();
        cartDAO.insertCart(cart);
        System.out.println(cart);
    }
    //删除
    public int delCart(ObjectId id) {
        Datastore ds = MorphiaUtil.getDB();
        Query<Cart> query = ds.createQuery(Cart.class);
        Query<Cart> que = query.field("id").equal(id);
        WriteResult delete = ds.delete(que);
        return delete.getN();
    }
    //根据购物车id查询
    public Cart findById(ObjectId id) {
        Datastore ds = MorphiaUtil.getDB();
        Query<Cart> query = ds.createQuery(Cart.class);
        Query<Cart> que = query.field("id").equal(id);
        Cart cart = query.get();
        return cart;
    }
    //根据用户id查询
    public Cart findByUId(ObjectId id) {
        Datastore ds = MorphiaUtil.getDB();
        Query<Cart> query = ds.createQuery(Cart.class);
        Query<Cart> que = query.field("userId").equal(id);
        Cart cart = query.get();
        return cart;
    }
    //根据商品id查询
    public Cart findByPId(ObjectId id) {
        Datastore ds = MorphiaUtil.getDB();
        Query<Cart> query = ds.createQuery(Cart.class);
        Query<Cart> que = query.field("productId").equal(id);
        Cart cart = query.get();
        return cart;
    }
    //根据用户id和商品id查询
    public Cart findByUIdAndPId(ObjectId userId, ObjectId productId) {
        Datastore ds = MorphiaUtil.getDB();
        Query<Cart> query = ds.createQuery(Cart.class).filter("userId", userId).filter("productId", productId);
        Cart cart = query.get();
        return cart;
    }
    public Cart findCartByUName(String userName) {
        Datastore ds = MorphiaUtil.getDB();
        Query<Cart> query = ds.createQuery(Cart.class);
        query.filter("userName",userName);
        Cart cart = query.get();
        return cart;

    }
    public List<Cart> findPageByUserId(ObjectId userId, int skip, int limit) {
        Datastore ds = MorphiaUtil.getDB();
        FindOptions findOptions = new FindOptions();
        findOptions.skip(skip).limit(limit);
        Query<Cart> query = ds.createQuery(Cart.class)
                .filter("userId", userId);
//                .offset(skip)
//                .limit(limit);
        List<Cart> list = query.asList(findOptions);
        return list;
    }
    //根据商品名称查询
    //public Cart findByPName(String name, User user)
    public Cart findByPName(String name, User user) {


        Datastore ds = MorphiaUtil.getDB();
        Query<Cart> query = ds.createQuery(Cart.class);
        /*Query<Cart> que2 = query.field("productName").equal(name);
        Cart cart = que2.get();
        return cart;*/
        System.out.println("11111"+query.get());
        query = query.field("userId").equal(user.getId())
                .field("productName").equal(name);
        //query = query.field("userId").equal(user.getId()).field("productName").equal(name);
        //query.field("userId").equal(user.getId());
        System.out.println("22222"+query.get());
        //query=query.field("productName").equal(name);
        //System.out.println("333333"+query.get());
        Cart cart = query.get();
        if (cart != null) {
            System.out.println("Found cart item: " + cart);
        } else {
            System.out.println("Cart item not found for user: " + user.getUsername() + " and product name: " + name);
        }
        //return cart;

        /*Datastore ds = MorphiaUtil.getDB();
        Query<Cart> query = ds.createQuery(Cart.class);

        // 设置查询条件：用户 ID 和产品名称
        query = query.field("userId").equal(user.getId())
                .field("productName").equal(name);
        System.out.println("query: " + query.toString());
        // 获取查询结果的迭代器
        MorphiaIterator<Cart, Cart> results = query.fetch();
        // 检查是否有匹配的文档
        if (results.hasNext()) {
            Cart cart = results.next();
            System.out.println("Found cart item: "+cart );
        } else {
            System.out.println("Cart item not found for user: " + user.getUsername() + " and product name: " + name);
        }*/
        return cart;

    }
    //查询全部
    public List<Cart> findAll() {
        Datastore ds = MorphiaUtil.getDB();
        Query<Cart> query = ds.createQuery(Cart.class);
        List<Cart> carts = query.asList();
        return carts;
    }
    //分页查询
    public List<Cart> findPage(int skip,int limit) {
        Datastore ds = MorphiaUtil.getDB();
        Query<Cart> query = ds.createQuery(Cart.class);
        FindOptions findOptions = new FindOptions();
        findOptions.skip(skip).limit(limit);
        List<Cart> carts = query.asList(findOptions);
        return carts;
    }
    //统计总数
    public long getCount() {
        return MorphiaUtil.getDB().getCount(Cart.class);
    }
    public long getCountByUId(ObjectId id) {
        Datastore ds = MorphiaUtil.getDB();
        Query<Cart> query = ds.createQuery(Cart.class);
        Query<Cart> que = query.field("userId").equal(id);
        Cart cart = query.get();
        if (cart != null) {
            System.out.println("Found cart item: " + cart);
            return cart.getNum();
        }else {
            System.out.println("Cart item not found for user: " + id);
        }
        return 1;
    }
    //修改购物车商品数量
    public int updateCart(Cart cart) {
        Datastore ds = MorphiaUtil.getDB();
        Query<Cart> query = ds.createQuery(Cart.class);
        Query<Cart> que = query.field("id").equal(cart.getId());
        UpdateOperations<Cart> update = ds.createUpdateOperations(Cart.class);
        if (cart.getNum()>0){
            update.set("num", cart.getNum());

        }else if (cart.getNum()<0){
            System.out.println("无法修改，请重新输入");
        }else if (cart.getNum()==0){
            delCart(cart.getId());
        }
        return 1;
    }

    public void updateNum(String id,int num){
        Datastore ds = MorphiaUtil.getDB();
        CartDAO cartDAO=new CartDAO();
        Cart cart=cartDAO.findById(new ObjectId(id));
        System.out.println(cart);
        cart.setNum(num);
        ds.save(cart);
    }

    public List<Cart> findByIds(List<ObjectId> cartIds) {
        Datastore ds =MorphiaUtil.getDB();
        Query<Cart> query = ds.createQuery(Cart.class);
        for (ObjectId cartId : cartIds) {
            query = query.field("userId").equal(cartId);
        }
        List<Cart> list = query.asList();

        return list;
    }

//    @Test
//    public void TestupdateNum(){
//        CartDAO cartDAO=new CartDAO();
//        cartDAO.updateNum("6696099f146500000d000908",2);
//
//    }
}
